package com.study.crypto.basic.signer;

import com.study.crypto.basic.signer.utils.CMSUtils;
import org.apache.http.util.Asserts;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.signers.SM2Signer;
import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CRL;

/**
 * 基于 sm2 算法的加密签名消息签名。国家标准 GB/T 35275 签名数据类型(signedData)
 * @author Songjin
 * @since 2021-02-17 20:09
 */
public class PKCS7GmSigner extends Signer {
    
    private final Certificate certificate;
    private final CRL[] crls;
    private final byte[] contentData;
    
    public PKCS7GmSigner(Certificate certificate, CRL[] crls, byte[] contentData) {
        this.certificate = certificate;
        this.crls = crls;
        this.contentData = contentData;
    }
    
    @Override
    public byte[] sign(byte[] inData, PrivateKey privateKey) throws GeneralSecurityException, IOException, CryptoException {
        Asserts.notNull(privateKey, "privateKey");
        Asserts.notNull(certificate, "certificate");
    
        CipherParameters parameters = ECUtil.generatePrivateKeyParameter(privateKey);
        SM2Signer sm2Signer = new SM2Signer();
        sm2Signer.init(true, parameters);
        sm2Signer.update(inData, 0, inData.length);
        byte[] signValue = sm2Signer.generateSignature();
        return CMSUtils.compositeSignedData(certificate, signValue, contentData, crls);
    }
    
    @Override
    public boolean verify(byte[] inData, byte[] signature, PublicKey publicKey) throws GeneralSecurityException {
        return false;
    }
    
}
